package com.jsbs.iam.common.redis.configure;

import org.apache.commons.lang3.StringUtils;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.ClusterServersConfig;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;

/**
 * @Description
 * @Author huak
 * @Date 2022/6/23 15:16
 * @Version 1.0
 **/
@Configuration
public class RedissonConfig {

    @Value("${spring.redis.cluster.nodes}")
    private String cluster;

    @Value("${spring.redis.password}")
    private String password;

    @Bean
    public RedissonClient getRedisson() throws IOException {
        String[] nodes = cluster.split(",");
        // redisson版本是3.5，集群的ip前面要加上“redis://”，不然会报错，3.2版本可不加
        for (int i = 0; i < nodes.length; i++) {
            nodes[i] = "redis://" + nodes[i];
        }
        RedissonClient redisson ;
        Config config = new Config();
        ClusterServersConfig clusterConfig = config.useClusterServers() // 这是用的集群server
                .setScanInterval(2000) // 设置集群状态扫描时间
                .addNodeAddress(nodes);
        if (StringUtils.isNotBlank(password)) {
            clusterConfig.setPassword(password);
        }
        redisson = Redisson.create(config);
        // 可通过打印来检测是否配置成功
        //System.out.println(redisson.getConfig().toJSON().toString());
        return redisson;
    }
}
